package com.fuqi.android.zhongcai.business.dinuan.view.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.bumptech.glide.Glide;
import com.fuqi.android.zhongcai.R;
import com.fuqi.android.zhongcai.base.Constants;
import com.fuqi.android.zhongcai.base.request.api.PushImgApi;
import com.fuqi.android.zhongcai.base.request.result.PushResult;
import com.fuqi.android.zhongcai.base.view.activity.BaseActivity;
import com.fuqi.android.zhongcai.base.view.widget.CustomProgress;
import com.fuqi.android.zhongcai.business.shuig.OrderDict;
import com.fuqi.android.zhongcai.business.shuig.request.api.OrderHandleApi;
import com.fuqi.android.zhongcai.business.shuig.request.result.OrderHandleResult;
import com.fuqi.android.zhongcai.business.shuig.view.widget.CJRow.ARResponse;
import com.fuqi.android.zhongcai.sql.CacheImg;
import com.fuqi.android.zhongcai.sql.dao.SQLDao;
import com.fuqi.android.zhongcai.utils.ActivityUtils;
import com.fuqi.android.zhongcai.utils.FileUtil;
import com.fuqi.android.zhongcai.utils.ImageUtils;
import com.fuqi.framework.network.code.HandleCode;
import com.fuqi.framework.network.http.RequestManager;
import com.fuqi.framework.utils.NetworkUtils;
import com.fuqi.framework.utils.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class DiNuanCompleteActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks,BGASortableNinePhotoLayout.Delegate{
    @Bind(R.id.iv_azwc_sbhb)
    ImageView mIvSbhb;
    @Bind(R.id.iv_azwc_wxts)
    ImageView mIvWxts;
    @Bind(R.id.iv_azwc_bytp)
    ImageView mIvBytp;
    @Bind(R.id.activity_discover_invest_publish_picture_iv)
    ImageView mIvPub;

    private BGASortableNinePhotoLayout ninePhotoLayout;

    private static final int REQUEST_CODE_PERMISSION_PHOTO_PICKER = 1;

    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_CHOOSE_PHOTO_SBHB = 2;
    private static final int REQUEST_CODE_CHOOSE_PHOTO_WXTS = 3;
    private static final int REQUEST_CODE_CHOOSE_PHOTO_BYTP = 7;

    private static final int REQUEST_CODE_PHOTO_PREVIEW = 12;
    private ArrayList<String> selectedPhotos = new ArrayList<>();
    private static final int MAX_PHOTO_COUNT = 15;
    private String sPathSbhb,sPathWxts,sPathBytp;
    private ArrayList<String> netPhotos = new ArrayList<>();

    ARResponse response;

    @OnClick({R.id.iv_azwc_sbhb,R.id.iv_azwc_wxts,R.id.iv_azwc_bytp,R.id.btn_submit, R.id.activity_discover_invest_publish_picture_iv})
    public void onClick(View v){
        switch (v.getId()) {
            case R.id.iv_azwc_sbhb:
                choicePhotoWrapper(1,REQUEST_CODE_CHOOSE_PHOTO_SBHB);
                break;
            case R.id.iv_azwc_wxts:
                choicePhotoWrapper(1,REQUEST_CODE_CHOOSE_PHOTO_WXTS);
                break;
            case R.id.iv_azwc_bytp:
                choicePhotoWrapper(1,REQUEST_CODE_CHOOSE_PHOTO_BYTP);
                break;
            case R.id.activity_discover_invest_publish_picture_iv:
                choicePhotoWrapper(MAX_PHOTO_COUNT,REQUEST_CODE_CHOOSE_PHOTO);
                break;
            case R.id.btn_submit:

                if(StringUtil.isEmpty(sPathSbhb) || StringUtil.isEmpty(sPathWxts) ||
                    StringUtil.isEmpty(sPathBytp) ){
                    ActivityUtils.toast("请上传图片。");
                    return;
                }
                selectedPhotos = ninePhotoLayout.getData();
                if(selectedPhotos == null || selectedPhotos.size() == 0){
                    ActivityUtils.toast("请上传图片。");
                    return;
                }

            netPhotos = new ArrayList<>();
            netPhotos.add(sPathSbhb);
            netPhotos.add(sPathWxts);
            netPhotos.add(sPathBytp);
            netPhotos.addAll(ninePhotoLayout.getData());
            if (NetworkUtils.isCanUploadImg(DiNuanCompleteActivity.this)) {
                doUpload();
            }else{
                CacheImg cacheImg = new CacheImg(response.getValue("ORDER_ID"),StringUtil.getListString(netPhotos), Constants.TYPE_DI_NUAN);
                SQLDao.getInstance(this).insertDic(cacheImg);

                doPublish();
            }
        }
    }

    Response.Listener<OrderHandleResult> respOrderHandleListener = new Response.Listener<OrderHandleResult>() {

        @Override
        public void onResponse(OrderHandleResult response) {
            CustomProgress.close();
            if (HandleCode.requestSuccess()) {
                ActivityUtils.toast("提交成功。");
                finish();
                Log.i("juner", "juner respListener response : ");
            } else {



            }
        }
    };


    Response.Listener<PushResult> respWorkersListener = new Response.Listener<PushResult>() {

        @Override
        public void onResponse(PushResult response) {
            CustomProgress.close();
            FileUtil.clearDir(FileUtil.getTempFile());
            if (HandleCode.requestSuccess()) {
                netPhotos.addAll(StringUtil.getList(response.getPath(),","));
//                if(netPhotos.size() == selectedPhotos.size()) {
                    doPublish();
//                }
                Log.i("juner", "juner respListener response : " + response.getPath());
            } else {
            }
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            CustomProgress.close();
            FileUtil.clearDir(FileUtil.getTempFile());
            Log.i("juner", "juner  error.getMessage(): " + error.getMessage());

        }
    };

    private void doPublish(){
        if(response != null) {
            if(netPhotos.size() > 3) {
                response.update("finishConfirmFile", netPhotos.get(0));  // 三保海报
                response.update("warrantyCardFile", netPhotos.get(1));  // 质保卡
                response.update("detailListFile", netPhotos.get(2));  //保压图
                response.update("ORDER_STATUS", OrderDict.StatusType.DDZT_AZWC);
                if (netPhotos != null && netPhotos.size() > 0)
                    response.update("finishFiles", StringUtil.getListString(netPhotos.subList(3,netPhotos.size()))); // 施工完成图片路径，多个路径中间用逗号分隔
                RequestManager.getInstance().call(new OrderHandleApi(
                        new OrderHandleApi.OrderHandleParams(response.getDataWithMap()), respOrderHandleListener, errorListener));
            }
            CustomProgress.show(DiNuanCompleteActivity.this,"正在提交...",true,null);
            Log.i("response : ", response.toString());
        }
    }

    private void doUpload(){
        ActivityUtils.toast("图片处理中...");
        ninePhotoLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                List<File> files = ImageUtils.makePaths2ImgFileList(netPhotos);
                netPhotos.clear();
                CustomProgress.show(DiNuanCompleteActivity.this, "正在上传...", true, null);
                PushImgApi p = new PushImgApi(respWorkersListener, errorListener, "files", files, null);
                RequestManager.getInstance().call(p);
            }
        },100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
            ninePhotoLayout.setData(BGAPhotoPickerActivity.getSelectedImages(data));
            mIvPub.setVisibility(View.GONE);
        } else if (requestCode == REQUEST_CODE_PHOTO_PREVIEW) {
            ninePhotoLayout.setData(BGAPhotoPickerPreviewActivity.getSelectedImages(data));
        } else if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO_SBHB) {
            sPathSbhb = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            showPic(sPathSbhb,mIvSbhb);
        }else if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO_WXTS) {
            sPathWxts = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            showPic(sPathWxts,mIvWxts);
        }else if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO_BYTP) {
            sPathBytp = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            showPic(sPathBytp,mIvBytp);
        }
    }

    private void showPic(String path,ImageView iv){
        Glide.with(DiNuanCompleteActivity.this)
                .load(path)
//                    .placeholder(R.drawable.default_empty_img)
                .crossFade()
                .centerCrop()
                .into(iv);
    }

    @Override
    public void initView() {
        titleBar.setTitle("上传图片");
        ninePhotoLayout = (BGASortableNinePhotoLayout) findViewById(R.id.activity_discover_invest_publish_nine_photo);
        ninePhotoLayout.init(DiNuanCompleteActivity.this);
        ninePhotoLayout.setDelegate(DiNuanCompleteActivity.this);
    }


    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        response = new ARResponse(getIntent().getStringExtra("response"));
    }

    @Override
    public boolean hasTitleBar() {
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_complete_azdn;
    }


    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PICKER)
    private void choicePhotoWrapper(int count,int requestCode) {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "ZhongCDownload");
            if(REQUEST_CODE_CHOOSE_PHOTO == requestCode)
                startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, count, ninePhotoLayout.getData()), requestCode);
            else
                startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, count, null), requestCode);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片", requestCode, perms);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper(MAX_PHOTO_COUNT,REQUEST_CODE_CHOOSE_PHOTO);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        ninePhotoLayout.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        startActivityForResult(BGAPhotoPickerPreviewActivity.newIntent(this, MAX_PHOTO_COUNT, models, models, position, false), REQUEST_CODE_PHOTO_PREVIEW);
    }

}
